package com.jn.servicedemo.service;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.Nullable;

import com.jn.servicedemo.event.MusicEvent;
import com.jn.servicedemo.views.MusicListActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

public class CustomService extends Service {

    private MediaPlayer mMediaPlayer;
    private OnMusicPlayStateChangeListener mOnMusicPlayStateChangeListener;
    private Cursor mCursor;

    @Override
    public void onCreate() {
        super.onCreate();
        initPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        /*String command = intent.getStringExtra("command");
        Log.d("asdf", "=======onStartCommand=======" + command);
        switch (command) {
            case Constants.COMMAND_PLAY:
                play();
                break;
            case Constants.COMMAND_PAUSE:
                pause();
                break;
            case Constants.COMMAND_LAST:
                last();
                break;
            case Constants.COMMAND_NEXT:
                next();
                break;
        }*/
        String data = intent.getStringExtra("data");
        //String title = intent.getStringExtra("title");
        //String artist = intent.getStringExtra("artist");
        Uri dataUri = Uri.parse(data);
        if (mMediaPlayer != null) {
            try {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(getApplicationContext(), dataUri);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
                /*if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onPlayStart();
                }*/
                EventBus.getDefault().post(new MusicEvent("play"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("asdf", "=======onUnbind=======");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d("asdf", "=======onRebind=======");
        super.onRebind(intent);
    }

    public final class MyBinder extends Binder {
        public CustomService getService() {
            return CustomService.this;
        }
    }

    private void initPlayer() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("asdf", "播放结束!");
                //mOnMusicPlayStateChangeListener.onPlayComplete();
                //EventBus.getDefault().post(new MusicEvent("complete"));
                playNextSong();
            }
        });
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {//解决开始播放就提示播放结束
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
    }

    public void setCursor(Cursor cursor) {
        mCursor = cursor;
    }

    private void playNextSong() {//自动播放下一首
        if (mCursor != null) {
            if (mCursor.moveToNext()) {//游标向后移动，如不成功走到 else if
                //mCurrPosition++;
            } else if (mCursor.moveToFirst()) { //游标移动到第一条数据
                //mCurrPosition = 0;
            }
            getDataByCursor(mCursor);
        }
        updateMusicInfoAndNotify();
    }

    private void getDataByCursor(Cursor cursor) {
        int titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        //媒体地址
        int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        if (titleIndex >= 0 && artistIndex >= 0) {
            String title = cursor.getString(titleIndex);
            String artist = cursor.getString(artistIndex);
            String data = cursor.getString(dataIndex);
            Uri dataUri = Uri.parse(data);
            if (mMediaPlayer != null) {
                try {
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(getApplicationContext(), dataUri);
                    mMediaPlayer.prepare();
                    mMediaPlayer.start();
                /*if (mOnMusicPlayStateChangeListener != null) {
                    mOnMusicPlayStateChangeListener.onPlayStart();
                }*/
                    EventBus.getDefault().post(new MusicEvent("play"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onMusicInfoChanged(title, artist);
            }
        }
    }

    public void play() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            /*if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onPlayStart();
            }*/
            EventBus.getDefault().post(new MusicEvent("play"));
        }
    }

    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            /*if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onPlayStop();
            }*/
            EventBus.getDefault().post(new MusicEvent("stop"));
        }
    }

    public void last() {
        if (mCursor != null) {
            if (mCursor.moveToPrevious()) { // 游标向前移动，如不成功走到 else if
                // mPrevPosition--;
            } else if (mCursor.moveToLast()) { // 游标移动到最后一条数据
                // mPrevPosition = mCursor.getCount() - 1;
            }
            getDataByCursor(mCursor);
        }
        Log.d("asdf", "=======last=======");
    }

    public void next() {
        if (mCursor != null) {
            if (mCursor.moveToNext()) { // 游标向后移动，如不成功走到 else if
                // mNextPosition++;
            } else if (mCursor.moveToFirst()) { // 游标移动到第一条数据
                // mNextPosition = 0;
            }
            getDataByCursor(mCursor);
        }
        Log.d("asdf", "=======next=======");
    }

    public int getDuration() {//获取音乐时长
        int duration = 0;
        if (mMediaPlayer != null) {
            duration = mMediaPlayer.getDuration();
        }
        return duration;
    }

    public int getCurrentPosition() {//当前播放时长
        int position = 0;
        if (mMediaPlayer != null) {
            position = mMediaPlayer.getCurrentPosition();
        }
        return position;
    }

    public boolean isPlaying() {//是否正在播放
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public void seekTo(int progress) {//改变进度
        if (mMediaPlayer != null) {
            Log.d("asdf", "seekTo ==" + progress);
            mMediaPlayer.seekTo(progress);
        }
    }

    public void setOnMusicPlayStateChangeListener(OnMusicPlayStateChangeListener l) {
        mOnMusicPlayStateChangeListener = l;
    }

    // 获取当前音乐标题
    public String getCurrentTitle() {
        if (mCursor != null) {
            int titleIndex = mCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            return mCursor.getString(titleIndex);
        }
        return null;
    }

    // 获取当前艺术家名称
    public String getCurrentArtist() {
        if (mCursor != null) {
            int artistIndex = mCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            return mCursor.getString(artistIndex);
        }
        return null;
    }


    public void updateMusicInfoAndNotify() {
        if (mCursor != null) {
            if (mCursor.isFirst() || mCursor.isLast() || mCursor.moveToNext()) {
                getDataByCursor(mCursor);
                EventBus.getDefault().post(new MusicEvent("infoChanged"));
            }
        }
    }





    public interface OnMusicPlayStateChangeListener {
        void onPlayStart();

        void onPlayStop();

        void onPlayComplete();

        void onMusicInfoChanged(String title, String artist);
    }
}
